<?php
require_once 'models/models_thanhtoan.php';
$tt=new models_thanhtoan();
$mod=$_GET['mod'];

if(isset($mod))
{
	switch ($mod)
	{
		case 'thanhtoan':{
			$i=0;
		if(isset($_SESSION['username']))
		{
			if (isset($_SESSION['cart']))
			{
				foreach ($_SESSION['cart'] as $key => $value) {	
			$mh=$tt->getmathang($key);
			$data = $tt->getuser($_SESSION['username']);
			$kh=$tt->getkhachhang($data['HoTen']);	
			if(!$kh){
				$tt->addkhachhang($data['HoTen'],$data['DiaChi'],$data['DienThoai'],$data['Email']);
				
			}
			if($_POST)
			{
			
				if($_POST['txtCaptcha'] == $_SESSION['security_code'])
					{
						if($i<1){
			$tt->addHoaDon($kh['MaKH'],gmdate("Y-m-d H:i:s", time()+7*3600), $kh['TenKH']);
						}
			$hd=$tt->gethoadon(gmdate("Y-m-d H:i:s", time()+7*3600));
			if($value['soluong']>$mh['SoLuong'])
			{
				$soluong=$mh['SoLuong']-$mh['SoLuong'];
			
				$tt->_addCTHoaHon($mh['MaMH'], $hd['MaHD'],$mh['SoLuong'], $value['gia']);
				$tt->updatemh($soluong, $mh['MaMH']);
			}else{
				$soluong=$mh['SoLuong']-$value['soluong'];
				$tt->_addCTHoaHon($mh['MaMH'], $hd['MaHD'],$value['soluong'], $value['gia']);
				$tt->updatemh($soluong, $mh['MaMH']);
			}
			echo '<script> window.location.href="index.php?mod=mua"</script>';
				}
			}
			$i++;	
				}
			require 'views/main/cart/thanhtoan.php';
			break;
			
			}
		}else 
		{ 
			if (isset($_SESSION['cart']))
			{
				foreach ($_SESSION['cart'] as $key => $value) {	
			$mh=$tt->getmathang($key);
			if($_POST)
			{
			
				if($_POST['txtCaptcha'] == $_SESSION['security_code'])
					{
				$kh=$tt->getkhachhang($_POST['txthovaten']);	
				if(!$kh){
				$tt->addkhachhang($_POST['txthovaten'],$_POST['txtdiachi'],$_POST['txtdienthoai'],$_POST['txtmail']);
				
				}
			
				$kh=$tt->getkhachhang($_POST['txthovaten']);	
					if($i<1){
			$tt->addHoaDon($kh['MaKH'],gmdate("Y-m-d H:i:s", time()+7*3600), $kh['TenKH']);
						}
				$hd=$tt->gethoadon(gmdate("Y-m-d H:i:s", time()+7*3600));
					if($value['soluong']>$mh['SoLuong'])
			{
				$soluong=$mh['SoLuong']-$mh['SoLuong'];
			
				$tt->_addCTHoaHon($mh['MaMH'], $hd['MaHD'],$mh['SoLuong'], $value['gia']);
				$tt->updatemh($soluong, $mh['MaMH']);
			}else{
				$soluong=$mh['SoLuong']-$value['soluong'];
				$tt->_addCTHoaHon($mh['MaMH'], $hd['MaHD'],$value['soluong'], $value['gia']);
				$tt->updatemh($soluong, $mh['MaMH']);
			}
				
				echo '<script> window.location.href="index.php?mod=mua"</script>';
			
			}
				
			}
			$i++;	
		}
		
		}
		require 'views/main/cart/thanhtoan.php';
			break;
		}
		}
		case 'mua':{
				unset($_SESSION['cart']);
				require_once 'views/main/cart/mua.php';
			break;
		}	
			
	}
}

	

?>
